package com.example.news123;

import android.os.Bundle;


import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.example.news123.ui.FourFragment;
import com.example.news123.ui.OneFragment;
import com.example.news123.ui.ThreeFragment;
import com.example.news123.ui.TwoFragment;
import com.example.news123.widget.bottomtab.BottomTabLayout;
import com.example.news123.widget.bottomtab.TabItem;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements BottomTabLayout.OnTabClickListener {

    private BottomTabLayout tab_layout;
    private ArrayList<TabItem> tabs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitle("缝盒聚怪");

        tab_layout = (BottomTabLayout) findViewById(R.id.tab_layout);

        initBottomTab();
        tab_layout.setCurrentTab(0);
    }

    private void initBottomTab() {
        tabs = new ArrayList<>();
        tabs.add(new TabItem(R.drawable.selector_tab_msg, R.string.wechat, OneFragment.class));
        tabs.add(new TabItem(R.drawable.selector_tab_contact, R.string.contacts, TwoFragment.class));
        tabs.add(new TabItem(R.drawable.selector_tab_moments, R.string.discover, ThreeFragment.class));
        tabs.add(new TabItem(R.drawable.selector_tab_profile, R.string.me, FourFragment.class));
        tab_layout.initData(tabs, this);
    }

    private Fragment lastFragment;

    @Override
    public void onTabClick(TabItem tabItem) {
        try {
            Fragment tmpFragment = getSupportFragmentManager().findFragmentByTag(tabItem.tagFragmentClz.getSimpleName());
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            if (tmpFragment == null) {
                tmpFragment = tabItem.tagFragmentClz.newInstance();
                transaction.add(R.id.fl_container, tmpFragment, tabItem.tagFragmentClz.getSimpleName());
                if (lastFragment != null) {
                    transaction.hide(lastFragment);
                }
                transaction.commitAllowingStateLoss();
            } else {
                transaction.show(tmpFragment);
                if (lastFragment != null) {
                    transaction.hide(lastFragment);
                }
                transaction.commitAllowingStateLoss();
            }
            lastFragment = tmpFragment;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
